var util = require('../../utils/util.js');
var api = require('../../config/api.js');

var app = getApp()
Page({
  data: {
    keywrod: '',
    searchStatus: false,
    goodsList: [],
    helpKeyword: [],
    historyKeyword: [],
    categoryFilter: false,
    currentSortType: 'default',
    currentSortOrder: '',
    filterCategory: [],
    defaultKeyword: {},
    hotKeyword: [],
    //酒店页面索引
    hotelIndex: 1, type: "",
    //景点页面索引
    sceneIndex: 1,
    //线路页面索引
    tourIndex: 1,
    //分页大小
    pageSize: 6,
    currentSortType: 'id',
    currentSortOrder: 'desc',
    categoryId: 0,
    winWidth: 0,
    winHeight: 0,
    // tab切换  
    currentTab: 0
  },
  //事件处理函数
  closeSearch: function () {
    wx.navigateBack()
  },
  clearKeyword: function () {
    this.setData({
      keyword: '',
      searchStatus: false
    });
  },
  onLoad: function (options) {
    this.setData({
      city: wx.getStorageSync("city"),
      startDate: wx.getStorageSync("startDate"),
      endDate: wx.getStorageSync("endDate"),
      type: wx.getStorageSync("type")
    })
    this.setData({
      keyword: '',
      page: 1,
      categoryId: 0,
      goodsList: []
    });
    this.getGoodsList();
    /** 
     * 获取系统信息 
     */
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },

  getSearchKeyword() {
    let that = this;
    util.request(api.SearchIndex).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          historyKeyword: res.data.historyKeywordList,
          defaultKeyword: res.data.defaultKeyword,
          hotKeyword: res.data.hotKeywordList
        });
      }
    });
  },

  inputChange: function (e) {

    this.setData({
      keyword: e.detail.value,
      searchStatus: false
    });
    // this.getHelpKeyword();
  },
  getHelpKeyword: function () {
    let that = this;
    util.request(api.SearchHelper, { keyword: that.data.keyword }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          helpKeyword: res.data
        });
      }
    });
  },
  inputFocus: function () {
    this.setData({
      searchStatus: false,
      goodsList: []
    });

    if (this.data.keyword) {
      this.getHelpKeyword();
    }
  },
  clearHistory: function () {
    this.setData({
      historyKeyword: []
    })

    util.request(api.SearchClearHistory, {}, 'POST')
      .then(function (res) {
        console.log('清除成功');
      });
  },
  getGoodsList: function () {
    //获取景点数据
    this.getSceneData();
    //获取酒店数据
    this.getHotelData();
    //获取线路数据
    this.getTourData();
  },
  getSceneData: function () {
    var that = this;
    //获取景点数据
    util.request(api.SceneSearchList, { keyword: that.data.keyword, pageNum: that.data.sceneIndex, pageSize: that.data.pageSize, orderType: that.data.currentSortType, isDesc: that.data.currentSortOrder, category: that.data.categoryId, regionName: that.data.city }).then(function (res) {
      if (res.code == 200) {
        that.setData({
          searchStatus: true,
          categoryFilter: false,
          sceneList: res.datas
        });
      }
      //重新获取关键词
      // that.getSearchKeyword();
    });
  },
  onKeywordTap: function (event) {

    this.getSearchResult(event.target.dataset.keyword);

  },
  getSearchResult(keyword) {

    this.setData({
      keyword: keyword,
      page: 1,
      categoryId: 0,
      goodsList: []
    });

    this.getGoodsList();
  },
  openSortFilter: function (event) {
    let currentId = event.currentTarget.id;
    switch (currentId) {
      case 'categoryFilter':
        this.setData({
          'categoryFilter': !this.data.categoryFilter,
          'currentSortOrder': 'asc'
        });
        break;
      case 'priceSort':
        let tmpSortOrder = 'asc';
        if (this.data.currentSortOrder == 'asc') {
          tmpSortOrder = 'desc';
        }
        this.setData({
          'currentSortType': 'price',
          'currentSortOrder': tmpSortOrder,
          'categoryFilter': false
        });

        this.getGoodsList();
        break;
      default:
        //综合排序
        this.setData({
          'currentSortType': 'default',
          'currentSortOrder': 'desc',
          'categoryFilter': false
        });
        this.getGoodsList();
    }
  },
  selectCategory: function (event) {
    let currentIndex = event.target.dataset.categoryIndex;
    let filterCategory = this.data.filterCategory;
    let currentCategory = null;
    for (let key in filterCategory) {
      if (key == currentIndex) {
        filterCategory[key].selected = true;
        currentCategory = filterCategory[key];
      } else {
        filterCategory[key].selected = false;
      }
    }
    this.setData({
      'filterCategory': filterCategory,
      'categoryFilter': false,
      categoryId: currentCategory.id,
      page: 1,
      goodsList: []
    });
    this.getGoodsList();
  },
  onKeywordConfirm(event) {
    this.getSearchResult(event.detail.value);
  },
  /** 
     * 滑动切换tab 
     */
  bindChange: function (e) {
    var that = this;
    that.setData({ currentTab: e.detail.current });

  },
  /** 
   * 点击tab切换 
   */
  swichNav: function (e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  //获取酒店数据
  getHotelData: function () {
    let that = this;
    var data = {
      pageSize: that.data.pageSize,
      pageNum: that.data.hotelIndex,
      regionName: that.data.city,
      startDate: that.data.startDay,
      endDate: that.data.endDay,
      keyWord: that.data.keyword,
      orderType: that.data.currentSortType,
      isDesc: that.data.currentSortOrder,
      category: that.data.categoryId
    }
    util.request(api.HotelList, data).then(function (res) {
      if (res.code == 200) {
        that.setData({
          hotels: res.datas
        });
      }
    });
  },
  getTourData: function () {
    let that = this;
    util.request(api.TourSearch, { keyword: that.data.keyword, pageNum: that.data.tourIndex, pageSize: that.data.pageSize, orderType: that.data.currentSortType, isDesc: that.data.currentSortOrder, typeId: "" }).then(function (res) {
      if (res.code == 200) {
        that.setData({
          searchStatus: true,
          categoryFilter: false,
          tourList: res.datas
        });
      }
      //重新获取关键词
      // that.getSearchKeyword();
    });
  },
  //上拉加载更多
  fnGetMore: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    that.fnGetMoreData(type);
  },
  fnGetMoreData: function (type) {
    var that = this;
    var pageSize = that.data.pageSize;
    var pageNum = 0;
    var url = "";
    if (type == 'hotel') {
      url = api.HotelList;
      pageNum = that.data.hotelIndex + 1;
      that.setData({
        hotelIndex: pageNum
      })
    } else if (type == "scene") {
      url = api.SceneSearchList;
      pageNum = that.data.sceneIndex + 1;
      that.setData({
        sceneIndex: pageNum
      })
    } else {
      url = api.TourSearch
      pageNum = that.data.tourIndex + 1;
      that.setData({
        tourIndex: pageNum
      })
    }
    wx.showLoading({
      title: '加载中...'
    });
    var data = {
      pageSize: that.data.pageSize,
      pageNum: pageNum,
      regionName: that.data.city,
      startDate: that.data.startDay,
      endDate: that.data.endDay,
      keyWord: that.data.keyword,
      orderType: that.data.currentSortType,
      isDesc: that.data.currentSortOrder,
      category: that.data.categoryId,
      typeId: ""
    }
    util.request(url, data).then(function (res) {
      wx.hideLoading();
      if (res.code == "200") {
        if (res.datas.hotels && res.datas.hotels.length > 0) {
          that.setData({
            hotels: that.data.hotels.concat(res.datas.hotels)
          })
        } else if (res.datas.scenes && res.datas.scenes.length > 0) {
          that.setData({
            sceneList: that.data.sceneList.concat(res.datas.scenes)
          })
        } else if (res.datas.tour && res.datas.tour.length > 0) {
          that.setData({
            tourList: that.data.tourList.concat(res.datas.tours)
          })
        } else {
          
          //减一页
          if (type == 'hotel') {
            that.setData({
              hotelIndex: pageNum - 1,
              noMore_hotel: true
            })
          } else if (type == 'scene') {
            that.setData({
              sceneIndex: pageNum - 1,
              noMore_scene: true
            })
          } else {
            that.setData({
              tourIndex: pageNum - 1,
              noMore_tour: true
            })
          }
          that.setData({

          });
        }
      } else {
        wx.showToast({
          title: '请求失败',
          image: '/static/images/icon_error.png'
        })
      }
    });
  }, fnShare: function (e) {
    var that = this;
    var path = "";
    var type = e.currentTarget.dataset.type;
    var goodsId = e.currentTarget.dataset.id;
    var imgUrl = e.currentTarget.dataset.url;
    var goodsName = e.currentTarget.dataset.name;
    var address = e.currentTarget.dataset.address;
    var price = e.currentTarget.dataset.price;
    var marketPrice = e.currentTarget.dataset.marketprice;
    if (type == 'hotel') {
      path = "/pages/hotelDetail/hoteldetail";
    } else if (type == "scene") {
      path = "/pages/sceneDetail/sceninfo";
    } else {
      path = "/pages/tourDetail/travelline"
    }
    app.fnShareGoods(path, goodsId, imgUrl, goodsName, type, address, price, marketPrice);
  },
})